import ntplib
import pytz
from datetime import datetime, timedelta


class NTPClient:
    """
    NTP客户端类，用于从网络时间服务器获取当前时间·防止weiApi接口失效·或者当前时间不是东八区时间
    """

    @staticmethod
    def get_time():
        # 最稳定的ntp服务器：上海交通大学网络中心
        ntp_server = '202.120.2.101'
        client = ntplib.NTPClient()
        while True:
            try:
                response = client.request(ntp_server, version=3)
                ntp_time = datetime.utcfromtimestamp(response.orig_time)
                local_tz = pytz.timezone('Asia/Shanghai')
                local_time = local_tz.fromutc(ntp_time)
                return local_time

            except Exception as e:
                print(f"获取网络时间失败: {e}")

    @staticmethod
    def increment_time_string(time_str, seconds=1):
        """
        递增时间字符串

        :param time_str: 时间字符串
        :param seconds: 要递增的秒数，默认为1秒
        :return: 递增后的时间字符串
        """
        dt = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
        new_dt = dt + timedelta(seconds=seconds)
        return new_dt.strftime("%Y-%m-%d %H:%M:%S")
